package net.fdukedom.epicurus.presentation;

import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.domain.util.UserHelper;

import javax.servlet.http.HttpServletRequest;

/**
 * Object to store data for logged in user.
 *
 * @author Dmitry Y. Kochelaev
 */
public final class SessionData {

    /**
     * Name of the HTTP session attribute that contains this session.
     */
    private static final String SESSION_ATTRIBUTE = "sessionData";

    /**
     * Logged in user id.
     */
    private int userId = -1;

    /**
     * Default constructor.
     */
    private SessionData() {
        //This is an utility class.
    }

    /**
     * Loads an instance of session data object from request for currently
     * logged in user.
     *
     * @param request HTTP request
     *
     * @return instance of session data.
     */
    public static SessionData getInstance(HttpServletRequest request) {
        SessionData result = (SessionData) request.getSession().getAttribute(SESSION_ATTRIBUTE);
        if (result == null) {
            result = new SessionData();
            request.getSession().setAttribute(SESSION_ATTRIBUTE, result);
        }
        return result;
    }

    /**
     * Clears session associated with request.
     *
     * @param request HTTP request.
     */
    public static void clearInstance(HttpServletRequest request) {
        request.getSession().removeAttribute(SESSION_ATTRIBUTE);
    }

    /**
     * Returns currently logged in user.
     *
     * @return currently logged in user
     */
    public User getUser() {
        return UserHelper.getInstance().load(userId);
    }

    /**
     * Sets user.
     *
     * @param userId user id
     */
    public void setUser(int userId) {
        this.userId = userId;
    }

    /**
     * Sets user.
     *
     * @param user user instance
     */
    public void setUser(User user) {
        this.userId = user.getId();
    }
}
